package cn.itcast.bos.web.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Actions
@Scope("propotype")
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	private Customer customer = new Customer();

	@Override
	public Customer getModel() {
		return customer;
	}

	@Action(value = "customer_sendSms")
	public String sendSum() throws UnsupportedEncodingException {
		String numeric = RandomStringUtils.randomNumeric(4);
		System.out.println(numeric);
		System.out.println(customer.getTelephone());
		// 将数据存到session中
		ServletActionContext.getRequest().getSession().setAttribute("numeric", numeric);
		// 編輯短信内容
		final String mag = "尊敬的用户你好，你的验证码为：" + numeric + ",有效期为60秒。祝您生活愉快！";
		/*
		 * String result = SmsUtils.sendSmsByHTTP(customer.getTelephone(), mag);
		 */
		// 调用MQ服务，发送一条消息
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", customer.getTelephone());
				mapMessage.setString("mag", mag);
				return mapMessage;
			}
		});
		return NONE;

		// String result = "000/XXXX";
		// if (result.startsWith("000")) {
		// return NONE;
		// } else {
		// throw new RuntimeException("消息发送失败，你的验证码是：" + numeric);
		// }
	}

	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		// 得到session里面的数据进行比较

		String attribute = (String) ServletActionContext.getRequest().getSession().getAttribute("numeric");
		System.out.println(attribute);
		System.out.println(customer.getTelephone());
		if (attribute == null || !attribute.equals(checkcode)) {
			System.out.println("发送的验证码有误！");
			return INPUT;
		}
		WebClient.create("http://localhost:8889/crm_management/service/customerService/customer/")
				.type(MediaType.APPLICATION_JSON).post(customer);
		System.out.println("用户注册成功！");
		// 邮箱绑定redis用来绑定时间，在规定时间有效
		// 完成生成一个激活码存到session中
		String activecode = RandomStringUtils.randomNumeric(32);
		redisTemplate.opsForValue().set("redisactivecode", activecode, 24, TimeUnit.HOURS);
		String content = "尊敬的客户你好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='" + MailUtils.activeUrl + "?telephone="
				+ customer.getTelephone() + "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
		System.err.println(customer.getTelephone());
		System.err.println(content);
		MailUtils.sendMail("我的第一份发送邮件", content, customer.getEmail(), activecode);
		return SUCCESS;
	}

	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action(value = "customer_mail")
	public String customer_mail() throws IOException {
		// 解决编码问题
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		// 激活码是否有效
		String redisActivecode = redisTemplate.opsForValue().get("redisactivecode");
		System.out.println(redisActivecode);
		if (redisActivecode == null || !redisActivecode.equals(activecode)) {
			// 这说明激活无效输出
			ServletActionContext.getResponse().getWriter().println("对不起，没有激活验证！");
		} else {
			// 激活验证已经通过
			// 进行验证
			Customer redisCustomer = WebClient
					.create("http://localhost:8889/crm_management/service/customerService/customer/telephone/"
							+ customer.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			System.out.println(redisCustomer.getType());
			if (redisCustomer.getType() == null || redisCustomer.getType() != 1) {
				// 我们没有对存取激活码
				WebClient.create("http://localhost:8889/crm_management/service/customerService/customer/update/"
						+ customer.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
				ServletActionContext.getResponse().getWriter().print("已激活！");
			} else {
				ServletActionContext.getResponse().getWriter().print("已激活,无需再次激活！");
			}
			// 清除激活码
			redisTemplate.delete(customer.getTelephone());
		}
		return checkcode;
	}

}
